#include <E32Math.h>

#include <MrLockUi.rsg>

#include "ClientServerCommon.h"
#include "ObserveServerSession.h"
#include "Logger.h"
#include "AppUi.h"

RObserverSession::RObserverSession()
:   RSessionBase()
{
}


TInt RObserverSession::Connect()
{
LOG_WRITE("RObserverSession::Connect");

	if (iConnected)
		return KErrNone;
	iConnected = ETrue;

	TInt err = StartServer();
	if (err == KErrNone)
	{
		err = CreateSession(KServerName, Version(), 0);
	}
	
	if (err != KErrNone)
	{
		iConnected = EFalse;
		DefAppUi;
		appUi->ShowErrorNoteL(R_TEXT_ERROR_START_SERVER);
	}
	return err;
}


TVersion RObserverSession::Version() const
{
	return(TVersion(KTimeServMajorVersionNumber, KTimeServMinorVersionNumber, KTimeServBuildVersionNumber));
}

void RObserverSession::ReloadSettings() const
{
	if (!iConnected)
		return ;
	SendReceive(EUpdateSettings);
}

TInt RObserverSession::StartServer()
{
	TInt result = CreateServerProcess();
	return  result;
}

TBool RObserverSession::ServerStarted()
{
	TFindServer findTimeServer(KServerName);
	TFullName name;

	TInt result = findTimeServer.Next(name);
	if (result == KErrNone)
	{// Server is running
		return ETrue;
	}
	return EFalse;
}

TInt RObserverSession::CreateServerProcess()
{
	if (RObserverSession::ServerStarted())
	{
LOG_WRITE("server already exists");
		return KErrNone;
	}

	TInt result;

	const TUidType serverUid(KNullUid, KNullUid, KServerUid3);

	RProcess server;

	_LIT(KStrEmpty,"");
	result = server.Create(KServerName, KStrEmpty, serverUid);
	server.SetParameter(10, 1);//start the server whatever
	if (result != KErrNone)
	{
		return  result;
	}
//Wait the server to start
	TRequestStatus rendezvousStatus;
	server.Rendezvous(rendezvousStatus);
	server.Resume();
	User::WaitForRequest(rendezvousStatus);
//server started
	server.Close();

	return  KErrNone;
}
